package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func main() {
	// 设置当前的主文件目录， main.go 所在的位置，添加到配置文件当中去
	viper.SetDefault("main", "D:\\gofiles\\go-learning-notes\\go-learning\\zap日志库")
	// 因为是个接口类型的values，所以还可以这样设置
	//viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})

	// 配置文件名， 不加扩展
	viper.SetConfigName("config") // name of config file (without extension)
	// 设置文件的扩展名
	viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
	// viper.SetConfigFile("config.yaml") // 代替上面俩
	// 查找配置文件所在路径
	viper.AddConfigPath("/etc/appname/") // path to look for the config file in
	// 可以调用多次，添加多个配置文件路径
	viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths
	// 在当前路径进行查找
	viper.AddConfigPath(".") // optionally look for config in the working directory

	// 开始查找并读取配置文件
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file: %w \n", err))
	}

	// 将当前的配置写入 'viper.AddConfigPath()' and 'viper.SetConfigName' 设置的文件
	//viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'
	//// 安全写，不会覆盖
	//viper.SafeWriteConfig()
	//// 写到另一个配置文件
	//viper.WriteConfigAs("/path/to/my/.config")
	//viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written
	//viper.SafeWriteConfigAs("/path/to/my/.other_config")

	//viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")

	// any approach to require this configuration into your program.
	// 将配置转换为 字节类型的slice，再读取
	//var yamlExample = []byte(`
	//Hacker: true
	//name: steve
	//hobbies:
	//- skateboarding
	//- snowboarding
	//- go
	//clothing:
	//  jacket: leather
	//  trousers: denim
	//age: 35
	//eyes : brown
	//beard: true
	//`)
	//
	//viper.ReadConfig(bytes.NewBuffer(yamlExample))

	viper.Get("name") // this would be "steve"

	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
	})
	viper.WatchConfig()

	type MysqlConfig struct {
		Host   string `mapstructure:"port"`
		DbName string `mapstructure:"dbname"`
		Port   int    `mapstructure:"port"`
	}

	type Config struct {
		Port        int    `mapstructure:"port"`
		Version     string `mapstructure:"version"`
		MysqlConfig `mapstructure:"mysql"`
	}

	var c Config
	_ = viper.Unmarshal(&c)
	fmt.Printf("c: %#v\n", c)

	//ser := &http.Server{}
	//
	//ser.Shutdown()

	//r := gin.Default()
	//r.GET("/version", func(c *gin.Context){
	//	c.JSON(http.StatusOK, gin.H{
	//		"name": "haungdonglin",
	//		"age": 18,
	//		// 读取配置里的 version
	//		"version": viper.Get("version").(string),
	//	})
	//})
	//// 获取配置文件中的端口号
	//r.Run(":" + viper.Get("port").(string))
}
